import { db, STORES } from './db'

// 获取每日营养数据
export const getDailyNutrition = async (userEmail, date) => {
  try {
    const diary = await db.getAll(STORES.DIARY_LIST)
    const userDiary = diary.filter(item => item.userEmail === userEmail && item.date === date)
    
    const total = userDiary.reduce((acc, item) => {
      return {
        calories: (acc.calories || 0) + Number(item.calories || 0),
        protein: (acc.protein || 0) + Number(item.protein || 0),
        carbs: (acc.carbs || 0) + Number(item.carbs || 0),
        fat: (acc.fat || 0) + Number(item.fat || 0)
      }
    }, { calories: 0, protein: 0, carbs: 0, fat: 0 })

    return {
      calories: Math.round(total.calories),
      protein: Math.round(total.protein),
      carbs: Math.round(total.carbs),
      fat: Math.round(total.fat)
    }
  } catch (error) {
    console.error('获取每日营养数据失败:', error)
    return { calories: 0, protein: 0, carbs: 0, fat: 0 }
  }
}

// 获取本周营养数据总和
export const getWeeklyNutrition = async (userEmail) => {
  try {
    const diary = await db.getAll(STORES.DIARY_LIST)
    const userDiary = diary.filter(item => item.userEmail === userEmail)
    
    // 获取本周的日期范围
    const now = new Date()
    const today = now.getDay()
    const startDate = new Date(now)
    startDate.setDate(now.getDate() - today)
    
    // 生成本周的日期数组
    const weekDates = Array.from({ length: 7 }, (_, i) => {
      const date = new Date(startDate)
      date.setDate(startDate.getDate() + i)
      return formatDate(date)
    })
    
    // 计算本周每天的数据
    const weekData = weekDates.map(date => {
      const dayDiary = userDiary.filter(item => item.date === date)
      const total = dayDiary.reduce((acc, item) => {
        return {
          calories: (acc.calories || 0) + Number(item.calories || 0),
          protein: (acc.protein || 0) + Number(item.protein || 0),
          carbs: (acc.carbs || 0) + Number(item.carbs || 0),
          fat: (acc.fat || 0) + Number(item.fat || 0)
        }
      }, { calories: 0, protein: 0, carbs: 0, fat: 0 })
      
      return {
        date: new Date(date).getDay(),
        calories: Math.round(total.calories),
        protein: Math.round(total.protein),
        carbs: Math.round(total.carbs),
        fat: Math.round(total.fat)
      }
    })

    // 计算本周数据总和
    const weekTotal = weekData.reduce((acc, day) => {
      return {
        calories: acc.calories + day.calories,
        protein: acc.protein + day.protein,
        carbs: acc.carbs + day.carbs,
        fat: acc.fat + day.fat
      }
    }, { calories: 0, protein: 0, carbs: 0, fat: 0 })

    // 确保返回的数据格式一致
    return {
      weekData: weekData.map(day => ({
        ...day,
        calories: Math.round(day.calories),
        protein: Math.round(day.protein),
        carbs: Math.round(day.carbs),
        fat: Math.round(day.fat)
      })),
      weekTotal: {
        calories: Math.round(weekTotal.calories),
        protein: Math.round(weekTotal.protein),
        carbs: Math.round(weekTotal.carbs),
        fat: Math.round(weekTotal.fat)
      }
    }
  } catch (error) {
    console.error('获取每周营养数据失败:', error)
    return {
      weekData: Array(7).fill({
        date: 0,
        calories: 0,
        protein: 0,
        carbs: 0,
        fat: 0
      }),
      weekTotal: { calories: 0, protein: 0, carbs: 0, fat: 0 }
    }
  }
}

// 获取卡路里目标
export const getCalorieGoal = async (userEmail) => {
  try {
    const goal = await db.get(STORES.CALORIE_GOAL, userEmail)
    return goal?.target || 2000
  } catch (error) {
    console.error('获取卡路里目标失败:', error)
    return 2000
  }
}

// 添加新的饮食记录
export const addDiaryRecord = async (record) => {
  try {
    await db.add(STORES.DIARY_LIST, {
      ...record,
      userEmail: record.userEmail,
      date: record.date,
      mealType: record.mealType,
      calories: Number(record.calories) || 0,
      protein: Number(record.protein) || 0,
      carbs: Number(record.carbs) || 0,
      fat: Number(record.fat) || 0,
      timestamp: Date.now()
    })
    return true
  } catch (error) {
    console.error('添加饮食记录失败:', error)
    return false
  }
}

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
} 